# encoding: utf-8
# author: 侯佳涛
# file_name: 01_mongo
# create_time: 2021/9/14, 下午5:16
from pymongo import MongoClient
from urllib.parse import quote_plus

# 权限认证登陆
user = 'python'
pwd = 'python'
host = '127.0.0.1'
port = 27017
uri = 'mongodb://%s:%s@%s' % (quote_plus(user), quote_plus(pwd), host)

client = MongoClient(uri, port=port)

collection = client['test']['stu']

# # 查找全部数据
# print(collection.find())
#
# for item in collection.find():
#     print(item)
#     raise Exception()

# # 查找一条数据
# ret = collection.find_one({'name': '郭靖'})
# print(ret)
# ret.pop('_id')  # 清除_id的键值对
# print(ret)

# # 插入数据
# ret = collection.insert([{'name': '侯佳涛', 'age': 25, 'gender': True}, {'name': '冯奇', 'age': 24, 'gender': False}])
# print(ret)

# # 更新数据
# # upsert参数如果设置为True，则先进行查询，如果没有就将该记录直接插入到文件中
# collection.update({'age': {'$lte': 10}}, {'$set': {'age': 0}}, multi=True, upsert=True)

# # 删除一条数据
# collection.delete_one({'age': 0})
# rets = collection.find()
# for ret in rets:
#     print(ret)

# 删除多条数据
collection.delete_many({'age': 19})
rets = collection.find()
for ret in rets:
    print(ret)

